import axios from 'axios'

export interface ChatMessage {
  id: string
  senderId: string
  senderName: string
  content: string
  timestamp: string
  type: 'TEXT' | 'IMAGE' | 'FILE'
  fileUrl?: string
}

export interface ChatRoom {
  id: string
  name: string
  type: 'COURSE' | 'GROUP' | 'PRIVATE'
  participants: string[]
  lastMessage?: ChatMessage
  unreadCount: number
}

export const chatService = {
  async getChatRooms() {
    try {
      const response = await axios.get('/api/chat/rooms')
      return response.data as ChatRoom[]
    } catch (error) {
      throw new Error('获取聊天室列表失败')
    }
  },

  async getChatRoomMessages(roomId: string) {
    try {
      const response = await axios.get(`/api/chat/rooms/${roomId}/messages`)
      return response.data as ChatMessage[]
    } catch (error) {
      throw new Error('获取聊天消息失败')
    }
  },

  async sendMessage(roomId: string, message: { 
    content: string, 
    type: 'TEXT' | 'IMAGE' | 'FILE', 
    fileUrl?: string 
  }) {
    try {
      const response = await axios.post(`/api/chat/rooms/${roomId}/messages`, message)
      return response.data as ChatMessage
    } catch (error) {
      throw new Error('发送消息失败')
    }
  },

  async createChatRoom(roomData: {
    name: string
    type: 'COURSE' | 'GROUP' | 'PRIVATE'
    participants: string[]
  }) {
    try {
      const response = await axios.post('/api/chat/rooms', roomData)
      return response.data as ChatRoom
    } catch (error) {
      throw new Error('创建聊天室失败')
    }
  },

  async joinChatRoom(roomId: string) {
    try {
      const response = await axios.post(`/api/chat/rooms/${roomId}/join`)
      return response.data
    } catch (error) {
      throw new Error('加入聊天室失败')
    }
  }
}
